package com.example.mtbatissource.file_up;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileUploadControlelr {

    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        String contentType = file.getContentType();
        String name = file.getName();
        byte[] bytes = file.getBytes();
        System.out.println(bytes);
        return "success";
    }

    @PostMapping("/good")
    public String good() throws Exception {
        uploadFilefg(new File("C:\\\\Users\\\\HXYD\\\\Downloads\\\\202409131609.pdf"));
        return "true";
    }

    /**
     * 将文件上传网盘
     */
    private void uploadFilefg(File file) throws Exception {
        if (!file.exists()) {
            throw new FileNotFoundException("File not found: " + file.getName());
        }

        // 设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        httpHeaders.add("x-aep-appkey", "123");
        String timestamp = String.valueOf(System.currentTimeMillis());
        httpHeaders.add("x-aep-timestamp", timestamp);
        String nonce = UUID.randomUUID().toString().replaceAll("-", "");
        httpHeaders.add("x-aep-nonce", nonce);
        // 签名算法 x-aep-signature = sha256(x-aep-timestamp + apptoken + x-aep-nonce + x-aep-timestamp)
        String signature = "4569877";
        httpHeaders.add("x-aep-signature", signature);

        // 构建请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("uid", "123");
        body.add("folder_name", "/gjj/bankrupt");
        body.add("type", "pdf");
        body.add("file", new FileSystemResource(file));

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, httpHeaders);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8888/file/upload", httpEntity, String.class);

        String responseBody = responseEntity.getBody();
    }
}
